<!--
 * @Description: 接口管理
 * @Author: wning
 * @Date: 2022-12-01 15:50:11
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-01 14:34:29
-->

<template>
  <div class="x-page-col">
    <div class="x-left" style="min-width: 300px; padding: 0">
      <div class="top">
        <el-dropdown style="margin-right: 15px" @command="handleCommand" v-hasPermi="['upms:Interface:add']">
          <el-button type="primary" plain>
            {{ $t('auth.interface.addModuule') }}<em class="el-icon-arrow-down el-icon--right"></em>
          </el-button>
          <el-dropdown-menu>
            <el-dropdown-item command="a">{{ $t('auth.interface.addRoot') }}</el-dropdown-item>
            <el-dropdown-item command="b">{{ $t('auth.interface.addSub') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- <el-button type="primary" @click="append()" :icon="buttonIcons('add')"> {{ $t('common.add') }}</el-button> -->
      </div>

      <Tree
        v-loading="treeLoading"
        ref="treeCom"
        :defaultProps="defaultProps"
        @handleNodeClick="handleNodeClick"
        :options="optionsTree"
        style="box-sizing: border-box; height: calc(100% - 60px); position: relative"
      >
        <template #btn="{ scope: { node, data } }">
          <i class="el-icon-edit" style="color: #4474f6" :title="$t('common.edit')" @click="() => edit(data)"></i>
          <i
            class="el-icon-delete"
            style="color: #f55248"
            :title="$t('common.delete')"
            @click="() => remove(node, data)"
          ></i>
        </template>
      </Tree>
    </div>
    <div class="x-right">
      <x-filter @search="handleSearch" @reset="handleReset">
        <x-filter-item :label="$t('auth.interface.apiName')">
          <el-input
            v-model="searchParams.apiName"
            :placeholder="$t('auth.interface.apiNamePlaceholder')"
            clearable
          ></el-input>
        </x-filter-item>
        <x-filter-item :label="$t('auth.interface.apiUrl')">
          <el-input
            v-model="searchParams.apiUrl"
            :placeholder="$t('auth.interface.apiUrlPlaceholder')"
            clearable
          ></el-input>
        </x-filter-item>
        <x-filter-item :label="$t('auth.interface.perms')" prop="perms">
          <el-input
            v-model="searchParams.perms"
            :placeholder="$t('auth.interface.permsPlaceholder')"
            clearable
          ></el-input>
        </x-filter-item>
        <x-filter-item :label="$t('auth.interface.public')">
          <x-select
            :placeholder="$t('auth.interface.all')"
            v-model="searchParams.state"
            :options="dictOptions['upms_api.state']"
            style="width: 100%"
          ></x-select>
        </x-filter-item>
      </x-filter>
      <!--数据面板-->
      <x-data>
        <!--数据面板按钮插糟-->
        <template #tool>
          <el-row type="flex" class="tools" justify="space-between">
            <el-col :span="12">
              <el-button
                v-hasPermi="['upms:Interface:add']"
                v-if="currentNode?.id"
                type="primary"
                @click="add"
                :icon="buttonIcons('add')"
              >
                {{ $t('common.add') }}</el-button
              >
            </el-col>
            <el-col :span="12" class="tools-config">
              <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
            </el-col>
          </el-row>
        </template>
        <x-table
          ref="tableCom"
          :pagination="pagination"
          :data-source="tableData"
          :loading="loading"
          :row-key="'id'"
          @on-change="handleTableChange"
          @on-selection-change="handleSelectionChange"
        >
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
          <el-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :min-width="item.minWidth || '-'"
            :width="item.width || 100"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <el-switch
                v-if="item.prop === 'state'"
                :value="scope.row[item.prop]"
                active-color="#4474F6"
                inactive-color="#A5A9B2"
                @change="handleChangeState(scope.row[item.prop], scope.row.id)"
                :disabled="!checkBntPermi('upms:Interface:state')"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
              <!-- <x-state-cell
                v-if="item.prop === 'state'"
                :stateClass="scope.row[item.prop] || scope.row[item.prop] === 0 ? 'success' : ''"
                :text="selectDictLabel(stateOption, scope.row[item.prop] + '')"
              /> -->
              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.opeartion')" width="160">
            <template #default="scope">
              <more-table-actions
                :action-list="actions"
                :permis-list="permissionsActions"
                :row="scope.row"
                @onActionClick="handleActions"
              />
            </template>
          </el-table-column>
        </x-table>
      </x-data>
    </div>

    <interface-dialog
      ref="interfaceDialog"
      :dict-options="dictOptions"
      @handleSuccess="getModuleTree"
      :options="optionsTree"
    ></interface-dialog>
  </div>
</template>
<script>
  // import {  } from '@/common/mixins'
  import {
    selectDictLabel,
    throttle,
    buttonIcons,
    TableListMixin,
    QueryDictMixin,
    PermissionsMixin
  } from '@package/utils'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import { columns, actions } from '../config/interface.js'
  import {
    apiPostInterfaceBathDelete,
    listUrl,
    apiPostInterfaceTree,
    apiPutDisable,
    apiPutEnable
  } from '../api/interface.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import InterfaceDialog from '../components/interfaceDialog.vue'
  import Tree from '../components/Tree.vue'

  const { cachedView } = pinias
  export default {
    name: 'Interface',
    components: {
      Tree,
      InterfaceDialog
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        buttonIcons,
        columns,
        actions,
        listUrl,
        disableMixinCreated: true,
        searchParams: {
          apiName: '',
          apiUrl: '',
          perms: '',
          state: '',
          apiType: 2
        },
        statusOptions: [],
        dictKeys: ['upms_api.api_type', 'upms_api.state'],
        tableData: [],
        defaultProps: {
          children: 'children',
          label: 'apiName'
        },
        optionsTree: [],
        currentNode: '',
        creatFlage: false,
        treeLoading: false
      }
    },
    computed: {
      ...mapState(cachedView, ['visitedViews'])
    },
    mounted() {
      this.creatFlage = true
      this.getModuleTree()
      this.initDictConfig()
    },
    activated() {
      console.log('---activated----')
      const temp = this.visitedViews.filter((v) => v.path === this.$route.path)
      if (this.disableMixinCreated && this.creatFlage && !temp) {
        console.log('---refresh----')
        this.getModuleTree()
        this.initDictConfig()
      }
    },
    methods: {
      selectDictLabel,
      // 左侧模块树
      getModuleTree() {
        this.treeLoading = true
        apiPostInterfaceTree({ apiType: 1 })
          .then((res) => {
            this.treeLoading = false
            if (res.code === EnumApiCode.Success) {
              this.optionsTree = res.data
              if (this.optionsTree?.length) {
                this.currentNode = !this.currentNode.id ? this.optionsTree[0] : this.currentNode
              } else {
                this.currentNode = {}
              }
              if (this.currentNode?.id) {
                this.$nextTick(() => {
                  this.$refs.treeCom.setCurrentNode(this.currentNode.id)
                  this.handleSearch({ parentId: this.currentNode.id })
                })
              }
            }
          })
          .finally(() => {
            this.treeLoading = false
          })
      },
      handleChangeState: throttle(async function (state, id) {
        const { code, msg } = state === 1 ? await apiPutDisable(id) : await apiPutEnable(id)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          await this.loadData()
        } else {
          this.$message.error(msg)
        }
      }, 1000),

      // 查询
      handleSearch(val) {
        this.searchParams.parentId = this.currentNode?.id ?? ''
        this.queryParam = { ...this.searchParams, ...val }
        this.loadData()
      },
      resetSearch() {
        this.queryParam = {
          parentId: this.currentNode?.id ?? ''
        }
        this.pagination.pageNum = 1
        this.loadData()
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改
            this.$refs.interfaceDialog.handleOpen(data)
            break
          case 'delete':
            this.$confirm(this.$t('auth.interface.deletePrmo'), this.$t('auth.interface.prompt'), {
              confirmButtonText: this.$t('common.sure'),
              cancelButtonText: this.$t('common.cancel')
            })
              .then(() => {
                apiPostInterfaceBathDelete(data.id).then((res) => {
                  if (res.code === EnumApiCode.Success) {
                    this.$message.success(this.$t('common.deleteSuccess'))
                  } else {
                    this.$message.error(res.msg)
                  }
                  this.loadData()
                })
              })
              .catch(() => {
                //
              })
            break
          case 'info':
            this.$refs.interfaceDialog.handleOpen(data)
            break
          default:
            break
        }
      },
      handleCommand(command) {
        if (command === 'a') {
          this.append({ parentId: 0 })
        } else {
          this.append({ parentId: this.currentNode.id })
        }
      },
      // 树点击事件
      handleNodeClick(data) {
        this.currentNode = data
        this.queryParam = {
          ...this.queryParam,
          parentId: this.currentNode.id
        }
        this.loadData()
      },
      // 新增模块
      append(data) {
        const parms = {
          apiType: '1',
          // parentId: 0
          ...data
        }
        this.$refs.interfaceDialog.handleOpen(parms)
      },
      // 修改模块
      edit(data) {
        const parms = {
          apiType: '1',
          ...data
        }
        this.$refs.interfaceDialog.handleOpen(parms)
      },
      // 删除模块
      remove(node, data) {
        if (this.queryParam.total) {
          this.$message.error(this.$t('auth.interface.deleteTips'))
          return
        }
        this.$confirm(this.$t('auth.interface.deletePrmo'), this.$t('auth.interface.prompt'), {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel')
        }).then(() => {
          this.handleDeleteInterFace(data.id)
        })
      },
      // 接口新增
      add() {
        const data = {
          parentId: this.currentNode.id,
          apiType: '2',
          state: '1'
        }
        this.$refs.interfaceDialog.handleOpen(data)
      },
      /**
       * 删除
       * @param id ID string
       */
      handleDelete(id) {
        this.handleDeleteInterFace(id)
      },
      /**
       * 重置查询
       *
       */
      handleReset() {
        this.searchParams = {
          apiName: '',
          apiUrl: '',
          perms: '',
          state: ''
        }
        this.resetSearch()
      },
      /**
       * 删除接口
       *
       */
      handleDeleteInterFace(id) {
        apiPostInterfaceBathDelete(id).then((res) => {
          if (res.code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.deleteSuccess'))
          } else {
            this.$message.error(res.msg)
          }
          this.getModuleTree()
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .top {
    margin-bottom: 16px;
    padding: 12px 15px;
    border-bottom: 1px solid #e0e0e0;
  }
  // .leftTree {
  //   width: 200px;
  // }
  // .rightContent {
  //   width: calc(100% - 200px);
  // }
  // .pageRank {
  //   box-sizing: border-box;
  //   display: flex;
  //   height: 100%;
  // }
</style>
<style lang="scss">
  /* element滚动条组件 隐藏水平滚动条 */
  .x-left .el-scrollbar__view {
    padding: 0 15px;
  }
  .x-left .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .is-horizontal {
    display: none;
  }
</style>
